package com.tanhua.dubbo.api;

import com.tanhua.domain.mongo.UserFrozen;
import org.apache.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ldy
 * @Package com.tanhua.dubbo.api
 * @date 2021/11/7 0007 下午 11:35
 */
@Service
public class UserFrozenApiImpl implements UserFrozenApi {
    @Autowired
    private MongoTemplate mongoTemplate;

    /**
     * 冻结用户
     *
     * @param userFrozen
     */
    @Override
    public void freezeUser(UserFrozen userFrozen) {
        mongoTemplate.insert(userFrozen);
    }

    /**
     * 解封用户
     *
     * @param userId
     */
    @Override
    public void thawUser(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        mongoTemplate.remove(query, UserFrozen.class);
    }

    /**
     * 根据用户id查找冻结状态
     *
     * @param userId
     * @return
     */
    @Override
    public UserFrozen findUserFrozenByUserId(Long userId) {
        Query query = Query.query(Criteria.where("userId").is(userId));
        UserFrozen userFrozen = mongoTemplate.findOne(query, UserFrozen.class);
        return userFrozen;
    }

    /**
     * 获取被冻结的用户的id集合
     *
     * @return
     */
    @Override
    public List<Long> getFrozenIds() {
        List<UserFrozen> userFrozenList = mongoTemplate.findAll(UserFrozen.class);
        if (userFrozenList == null || userFrozenList.size() == 0) {
            return null;
        }
        List<Long> frozenIdList = new ArrayList<>();
        for (UserFrozen userFrozen : userFrozenList) {
            frozenIdList.add(userFrozen.getUserId());
        }
        return frozenIdList;
    }
}
